package com.binfenhulian.chinaenergy.ces.manage.framework.config;

import com.binfenhulian.chinaenergy.ces.utils.json.JsonUtil;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by wanghjbuf on 2018/3/8.
 */
public class JsonHandler implements TypeHandler<Object> {

    private final String SPLIT = "$$";
    private static final Logger log = LoggerFactory.getLogger(JsonHandler.class);

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException {
        if (o == null) {
            preparedStatement.setString(i, null);
            return;
        }
        String json = JsonUtil.toJson(o);
        String clazzName = o.getClass().getName();
        log.info("JsonHandler:" + json);
        preparedStatement.setString(i, json + SPLIT + clazzName);
    }

    @Override
    public Object getResult(ResultSet resultSet, String columnName) throws SQLException {
        String res = resultSet.getString(columnName);
        int index = res.lastIndexOf(SPLIT);
        if (index == -1) {
            return null;
        }
        String json = res.substring(0, index);
        String clazzName = res.substring(index + 2);
        Class<?> clazz = null;
        try {
            clazz = Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            log.error("ClassNotFount:" + clazzName);
        }
        return JsonUtil.fromJson(json, clazz);
    }

    @Override
    public Object getResult(ResultSet resultSet, int i) throws SQLException {
        String res = resultSet.getString(i);
        int index = res.lastIndexOf(SPLIT);
        String json = res.substring(0, index);
        String clazzName = res.substring(index + 2);
        Class<?> clazz = null;
        try {
            clazz = Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            log.error("ClassNotFount:" + clazzName);
        }
        return JsonUtil.fromJson(json, clazz);
    }

    @Override
    public Object getResult(CallableStatement callableStatement, int i) throws SQLException {
        String res = callableStatement.getString(i);
        int index = res.lastIndexOf(SPLIT);
        String json = res.substring(0, index);
        String clazzName = res.substring(index + 2);
        Class<?> clazz = null;
        try {
            clazz = Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            log.error("ClassNotFount:" + clazzName);
        }
        return JsonUtil.fromJson(json, clazz);
    }

}
